package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.AddressUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.quartz.domain.HatchetAcqJifen;
import com.ruoyi.quartz.service.IHatchetAcqJifenService;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetMessage;
import com.ruoyi.system.domain.HatchetMoneyChange;
import com.ruoyi.system.domain.HatchetOrderPayment;
import com.ruoyi.system.domain.UserRelation;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetMessageService;
import com.ruoyi.system.service.IHatchetMoneyChangeService;
import com.ruoyi.system.service.IHatchetOrderPaymentService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.IUserRelationService;
import com.ruoyi.system.vo.StringUtilsss;

/**
 * 积分记录 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-03-07
 */
@Controller
@RequestMapping("/system/hatchetAcqJifen")
public class HatchetAcqJifenController extends BaseController {
	private String prefix = "system/hatchetAcqJifen";

	@Autowired
	private IHatchetAcqJifenService hatchetAcqJifenService;
	@Autowired
	private IHatchetMerchantService merchantService;
	@Autowired
	private IHatchetAgentService agentService;
	@Autowired
	private ISysDictDataService sysDictDataService;
	@Autowired
	private IHatchetMoneyChangeService changeService;
	@Autowired
	private IHatchetMessageService messageService;
	@Autowired
	private IUserRelationService relationService;
	@Autowired
	private IHatchetOrderPaymentService orderPaymentService;
	
	@RequiresPermissions("system:hatchetAcqJifen:view")
	@GetMapping()
	public String hatchetAcqJifen() {
		return prefix + "/hatchetAcqJifen";
	}

	/**
	 * 查询积分记录列表
	 */
	@RequiresPermissions("system:hatchetAcqJifen:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(HatchetAcqJifen hatchetAcqJifen) {
		BigDecimal sumMoney = hatchetAcqJifenService.selectSumMoney(hatchetAcqJifen);
		if (StringUtils.isNotEmpty(hatchetAcqJifen.getUserId())) {
			HatchetMerchant merchant = merchantService.selectHatchetMerchantByNo(hatchetAcqJifen.getUserId());
			if (merchant != null) {
				hatchetAcqJifen.setUserId(merchant.getID());
			} else {
				return getDataTable(new ArrayList<>());
			}
		}
		startPage();
		List<HatchetAcqJifen> list = hatchetAcqJifenService.selectHatchetAcqJifenList(hatchetAcqJifen);
		if (StringUtils.isNotEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				// 设置总结算金额
				if (i == 0) {
					list.get(i).setSumMoney(sumMoney);
				}
				// 匹配商户编号和商户名称
				if (StringUtils.isNotEmpty(list.get(i).getUserId())) {
					HatchetMerchant merchant = merchantService.selectHatchetMerchantById(list.get(i).getUserId());
					if (StringUtils.isNotNull(merchant)) {
						list.get(i).setUserNo(merchant.getMerchantNo());
						list.get(i).setUserName(merchant.getMerchantCnName());
					}
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 导出积分记录列表
	 */
	@RequiresPermissions("system:hatchetAcqJifen:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(HatchetAcqJifen hatchetAcqJifen) {
		List<HatchetAcqJifen> list = hatchetAcqJifenService.selectHatchetAcqJifenList(hatchetAcqJifen);
		ExcelUtil<HatchetAcqJifen> util = new ExcelUtil<HatchetAcqJifen>(HatchetAcqJifen.class);
		return util.exportExcel(list, "hatchetAcqJifen");
	}

	/**
	 * 分润下发
	 */
	@RequiresPermissions("system:hatchetAcqJifen:remove")
	@Log(title = "分润下发", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	@Transactional
	public AjaxResult remove(String ids) {
		List<String> result = Arrays.asList(ids.split(","));
		String rate1 = sysDictDataService.selectDictLabel("jifen_rate", "1");// 普通用户分润比例
		String rate2 = sysDictDataService.selectDictLabel("jifen_rate", "2");// 黄金会员分润比例
		String rate3 = sysDictDataService.selectDictLabel("jifen_rate", "3");// 经纪人分润比例
		String rate4 = sysDictDataService.selectDictLabel("jifen_rate", "4");// 运营商分润比例
		String rate5 = sysDictDataService.selectDictLabel("jifen_rate", "5");// 商务中心分润比例
		String rate6 = sysDictDataService.selectDictLabel("jifen_rate", "6");// 联创分润比例
		for (String string : result) {
			HatchetAcqJifen acqJifen = hatchetAcqJifenService.selectHatchetAcqJifenById(string);
			HatchetMerchant mer = merchantService.selectHatchetMerchantById(acqJifen.getUserId());
			//获取订单的时间
			HatchetOrderPayment orderPayment = orderPaymentService.selectHatchetOrderPaymentByOrder(acqJifen.getOrderId());
			if (mer != null) {
				HatchetAgent agent = agentService.selectHatchetAgentById(mer.getAgentId());
				if ("2".equals(acqJifen.getBizType())) {
					// 各级差金额
					BigDecimal money1 = acqJifen.getProductAmount()
							.multiply(new BigDecimal(rate2).subtract(new BigDecimal(rate1)))
							.setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal money2 = acqJifen.getProductAmount()
							.multiply(new BigDecimal(rate3).subtract(new BigDecimal(rate2)))
							.setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal money3 = acqJifen.getProductAmount()
							.multiply(new BigDecimal(rate4).subtract(new BigDecimal(rate3)))
							.setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal money4 = acqJifen.getProductAmount()
							.multiply(new BigDecimal(rate5).subtract(new BigDecimal(rate4)))
							.setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal money5 = acqJifen.getProductAmount()
							.multiply(new BigDecimal(rate6).subtract(new BigDecimal(rate5)))
							.setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal money;
					String msg = null;
					BigDecimal aa = null;
					if ("1".equals(agent.getTYPE())) {
						aa = money3;
					} else if ("2".equals(agent.getTYPE())) {
						aa = money3.add(money4);
					} else if ("3".equals(agent.getTYPE())) {
						aa = money3.add(money4).add(money5);
					}

					if (acqJifen.getUserId() != null) {
						UserRelation userRelation1 = new UserRelation();
						userRelation1.setUid(mer.getID());
						if (orderPayment != null) {
							userRelation1.setCreateTime(orderPayment.getCreateTime());
						}else {
							userRelation1.setCreateTime(acqJifen.getSettleDate());
						}
						UserRelation userRelation = relationService.findByTime(userRelation1);
						if (userRelation != null) {
							if ("3".equals(userRelation.getLevel())) {
								money = money1.add(money2);
								HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
										"10B", "10K", money, mer.getMerchantNo(), acqJifen.getOrderId(), "10B",
										new Date());
								changeService.insertHatchetMoneyChange(moneyChange);
								msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money
										+ "元!";
								HatchetMessage hatchetMessage = new HatchetMessage(StringUtilsss.randomUUID(), "积分收益",
										msg, "5", "0", mer.getID(), mer.getPHONE(), mer.getID(), new Date(), money + "",
										null, null);
								messageService.insertHatchetMessage(hatchetMessage);
								mer.setTotalMoney(mer.getTotalMoney().add(money));

								// 通过代理商等级获取经纪人对其分润
								mer.setExamineResult(AddressUtils.contributeMoney(mer.getExamineResult(), aa,
										AddressUtils.INCOME_JF));
								mer.setChinaRegionId(AddressUtils.contributeMoney(mer.getChinaRegionId(), aa,
										AddressUtils.INCOME_JF));
								merchantService.updateHatchetMerchant(mer);
							}

							if ("2".equals(userRelation.getLevel())) {
								//判断是否为经理，是按等级为3划分，否按2划分
								if (mer.getSubmitReexamineTime() == null) {
									// 自己拿2-1的分润
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money1, mer.getMerchantNo(), acqJifen.getOrderId(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money1
											+ "元!";
									HatchetMessage hatchetMessage = new HatchetMessage(StringUtilsss.randomUUID(), "积分收益",
											msg, "5", "0", mer.getID(), mer.getPHONE(), mer.getID(), new Date(),
											money1 + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage);
									mer.setTotalMoney(mer.getTotalMoney().add(money1));
									merchantService.updateHatchetMerchant(mer);

									// 经纪人拿3-2的分润
									HatchetMerchant merchant = merchantService
											.selectHatchetMerchantById(userRelation.getU2id());
									HatchetMoneyChange moneyChange1 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money2, merchant.getMerchantNo(), acqJifen.getOrderId(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange1);
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money2
											+ "元!";
									HatchetMessage hatchetMessage1 = new HatchetMessage(StringUtilsss.randomUUID(), "积分收益",
											msg, "5", "0", merchant.getID(), merchant.getPHONE(), merchant.getID(),
											new Date(), money2 + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage1);
									merchant.setTotalMoney(merchant.getTotalMoney().add(money2));

									// 通过代理商等级获取经纪人对其分润
									merchant.setExamineResult(AddressUtils.contributeMoney(merchant.getExamineResult(), aa,
											AddressUtils.INCOME_JF));
									merchant.setChinaRegionId(AddressUtils.contributeMoney(merchant.getChinaRegionId(), aa,
											AddressUtils.INCOME_JF));
									merchantService.updateHatchetMerchant(merchant);
								} else {
									money = money1.add(money2);
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money, mer.getMerchantNo(), acqJifen.getOrderId(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money
											+ "元!";
									HatchetMessage hatchetMessage = new HatchetMessage(StringUtilsss.randomUUID(), "积分收益",
											msg, "5", "0", mer.getID(), mer.getPHONE(), mer.getID(), new Date(), money + "",
											null, null);
									messageService.insertHatchetMessage(hatchetMessage);
									mer.setTotalMoney(mer.getTotalMoney().add(money));

									// 通过代理商等级获取经纪人对其分润
									mer.setExamineResult(AddressUtils.contributeMoney(mer.getExamineResult(), aa,
											AddressUtils.INCOME_JF));
									mer.setChinaRegionId(AddressUtils.contributeMoney(mer.getChinaRegionId(), aa,
											AddressUtils.INCOME_JF));
									merchantService.updateHatchetMerchant(mer);

								}
								

							}

							if ("1".equals(userRelation.getLevel())) {
								HatchetMerchant merchant = null;
								HatchetMerchant merchant2 = null;
								// uid1拿2-1的分润,黄金会员的值
								String  u1Id = userRelation.getU1id();
								String u1ids[] = u1Id.split(",");
								if (u1ids.length == 2) {
									merchant = merchantService.selectHatchetMerchantById(u1ids[0]);
									merchant2 = merchantService.selectHatchetMerchantById(u1ids[1]);
								}else {
									merchant = merchantService.selectHatchetMerchantById(u1ids[0]);
									merchant2 = merchantService.selectHatchetMerchantById(userRelation.getU2id());
								}
								
								
								if (merchant != null) {
									// 黄金会员
									HatchetMoneyChange moneyChange1 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money1, merchant.getMerchantNo(), acqJifen.getOrderId(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange1);
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money1
											+ "元!";
									HatchetMessage hatchetMessage1 = new HatchetMessage(StringUtilsss.randomUUID(),
											"积分收益", msg, "5", "0", merchant.getID(), merchant.getPHONE(),
											merchant.getID(), new Date(), money1 + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage1);
									merchant.setTotalMoney(merchant.getTotalMoney().add(money1));
									merchantService.updateHatchetMerchant(merchant);
									// 经纪人
									HatchetMoneyChange moneyChange2 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money2, merchant2.getMerchantNo(), acqJifen.getOrderId(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange2);
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money2
											+ "元!";
									HatchetMessage hatchetMessage2 = new HatchetMessage(StringUtilsss.randomUUID(),
											"积分收益", msg, "5", "0", merchant2.getID(), merchant2.getPHONE(),
											merchant2.getID(), new Date(), money2 + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage2);
									merchant2.setTotalMoney(merchant2.getTotalMoney().add(money2));

									// 通过代理商等级获取经纪人对其分润
									merchant2.setExamineResult(AddressUtils
											.contributeMoney(merchant2.getExamineResult(), aa, AddressUtils.INCOME_JF));
									merchant2.setChinaRegionId(AddressUtils
											.contributeMoney(merchant2.getChinaRegionId(), aa, AddressUtils.INCOME_JF));
									merchantService.updateHatchetMerchant(merchant2);

								} else {
									money = money1.add(money2);
									HatchetMoneyChange moneyChange2 = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money, merchant2.getMerchantNo(), acqJifen.getOrderId(),
											"10B", new Date());
									changeService.insertHatchetMoneyChange(moneyChange2);
									msg = "恭喜您，客户" + StringUtils.phoneString(mer.getPHONE()) + "通过积分兑换为您贡献收益" + money
											+ "元!";
									HatchetMessage hatchetMessage2 = new HatchetMessage(StringUtilsss.randomUUID(),
											"积分收益", msg, "5", "0", merchant2.getID(), merchant2.getPHONE(),
											merchant2.getID(), new Date(), money + "", null, null);
									messageService.insertHatchetMessage(hatchetMessage2);
									merchant2.setTotalMoney(merchant2.getTotalMoney().add(money));

									// 通过代理商等级获取经纪人对其分润
									merchant2.setExamineResult(AddressUtils
											.contributeMoney(merchant2.getExamineResult(), aa, AddressUtils.INCOME_JF));
									merchant2.setChinaRegionId(AddressUtils
											.contributeMoney(merchant2.getChinaRegionId(), aa, AddressUtils.INCOME_JF));
									merchantService.updateHatchetMerchant(merchant2);
								}
							}

							// 代理商分润
							BigDecimal agentMoney;
							if (!"null".equals(userRelation.getU3id())) {
								// 运营商分润
								HatchetAgent agent1 = agentService.selectHatchetAgentById(userRelation.getU3id());
								HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
										"10B", "10K", money3, agent1.getAgentNo(), acqJifen.getOrderId(), "10B",
										new Date());
								changeService.insertHatchetMoneyChange(moneyChange);
								agent1.setTotalMoney(agent1.getTotalMoney().add(money3));
								agentService.updateHatchetAgent(agent1);
							}

							if (!"null".equals(userRelation.getU4id())) {
								if (!"null".equals(userRelation.getU3id())) {
									HatchetAgent agent1 = agentService.selectHatchetAgentById(userRelation.getU4id());
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money4, agent1.getAgentNo(), acqJifen.getOrderId(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									agent1.setTotalMoney(agent1.getTotalMoney().add(money4));
									agentService.updateHatchetAgent(agent1);
								} else {
									agentMoney = money4.add(money3);
									HatchetAgent agent1 = agentService.selectHatchetAgentById(userRelation.getU4id());
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", agentMoney, agent1.getAgentNo(), acqJifen.getOrderId(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									agent1.setTotalMoney(agent1.getTotalMoney().add(agentMoney));
									agentService.updateHatchetAgent(agent1);
								}
							}

							if (!"null".equals(userRelation.getU5id())) {
								HatchetAgent agent1 = agentService.selectHatchetAgentById(userRelation.getU5id());
								if (!"null".equals(userRelation.getU4id())) {
									// 联创分润
									HatchetMoneyChange moneyChange = new HatchetMoneyChange(StringUtilsss.randomUUID(),
											"10B", "10K", money5, agent1.getAgentNo(), acqJifen.getOrderId(), "10B",
											new Date());
									changeService.insertHatchetMoneyChange(moneyChange);
									agent1.setTotalMoney(agent1.getTotalMoney().add(money5));
									agentService.updateHatchetAgent(agent1);
								} else {
									if (!"null".equals(userRelation.getU3id())) {
										agentMoney = money5.add(money4);
										HatchetMoneyChange moneyChange = new HatchetMoneyChange(
												StringUtilsss.randomUUID(), "10B", "10K", agentMoney,
												agent1.getAgentNo(), acqJifen.getOrderId(), "10B", new Date());
										changeService.insertHatchetMoneyChange(moneyChange);
										agent1.setTotalMoney(agent1.getTotalMoney().add(agentMoney));
										agentService.updateHatchetAgent(agent1);
									} else {
										agentMoney = money5.add(money4).add(money3);
										HatchetMoneyChange moneyChange = new HatchetMoneyChange(
												StringUtilsss.randomUUID(), "10B", "10K", agentMoney,
												agent1.getAgentNo(), acqJifen.getOrderId(), "10B", new Date());
										changeService.insertHatchetMoneyChange(moneyChange);
										agent1.setTotalMoney(agent1.getTotalMoney().add(agentMoney));
										agentService.updateHatchetAgent(agent1);
									}

								}

							}

						}

					}
					// 修改订单状态
					acqJifen.setBizType("1");
					hatchetAcqJifenService.updateHatchetAcqJifen(acqJifen);
					//修改订单是否清分
					if (orderPayment != null) {
						orderPayment.setSettleListStatus("10B");
						orderPaymentService.updateHatchetOrderPayment(orderPayment);
						
					}
				}
			}
		}
		return AjaxResult.success("分润完成");
	}

//	/*
//	 * 递归寻找上级经纪人
//	 */
//	public HatchetMerchant findParentByLevel(HatchetMerchant mer, int plevel) {
//		int level = 0;
//		HatchetMerchant parent = null;
//		while (level < plevel) {
//			parent = merchantService.getMerchantByPhoneOrLinkPhone(mer.getParentPhone());
//			if (parent != null) {
//				level = Integer.parseInt(parent.getLEVEL());
//				mer = parent;
//			}
//		}
//		return parent;
//	}

}
